package model

import (
	"context"
	"fmt"

	"github.com/Masterminds/squirrel"
	"github.com/zeromicro/go-zero/core/stores/cache"
	"github.com/zeromicro/go-zero/core/stores/sqlc"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

var _ LeaderboardsModel = (*customLeaderboardsModel)(nil)

type (
	// LeaderboardsModel is an interface to be customized, add more methods here,
	// and implement the added methods in customLeaderboardsModel.
	LeaderboardsModel interface {
		leaderboardsModel
		RowBuilder() squirrel.SelectBuilder
		Truncate(ctx context.Context)
		FindAll(ctx context.Context) ([]*Leaderboards, error)
		FindAllEx(Current int64, PageSize int64) (*[]Leaderboards, error)
		Count() (int64, error)
	}

	customLeaderboardsModel struct {
		*defaultLeaderboardsModel
	}
)

// NewLeaderboardsModel returns a model for the database table.
func NewLeaderboardsModel(conn sqlx.SqlConn, c cache.CacheConf) LeaderboardsModel {
	return &customLeaderboardsModel{
		defaultLeaderboardsModel: newLeaderboardsModel(conn, c),
	}
}

func (m *defaultLeaderboardsModel) RowBuilder() squirrel.SelectBuilder {
	return squirrel.Select(leaderboardsRows).From(m.table)
}

func (m defaultLeaderboardsModel) Truncate(ctx context.Context) {
	build := m.RowBuilder()
	query, values, err := build.ToSql()
	if err == nil {
		var resp []*Leaderboards
		err = m.QueryRowsNoCacheCtx(ctx, &resp, query, values...)
		if err == nil {
			for _, r := range resp {
				m.Delete(ctx, r.Id)
			}
			m.ExecNoCacheCtx(ctx, fmt.Sprintf("TRUNCATE %s", m.tableName()))
		}
	}
}

func (m defaultLeaderboardsModel) FindAll(ctx context.Context) ([]*Leaderboards, error) {
	build := m.RowBuilder()
	query, values, err := build.ToSql()
	if err != nil {
		return nil, nil
	}

	var resp []*Leaderboards
	err = m.QueryRowsNoCacheCtx(ctx, &resp, query, values...)
	switch err {
	case nil:
		return resp, nil
	default:
		return nil, err
	}
}

func (m *defaultLeaderboardsModel) FindAllEx(Current int64, PageSize int64) (*[]Leaderboards, error) {
	query := fmt.Sprintf("select * from %s  limit ?,?", m.table)
	var resp []Leaderboards
	err := m.CachedConn.QueryRowsNoCache(&resp, query, (Current-1)*PageSize, PageSize)
	switch err {
	case nil:
		return &resp, nil
	case sqlc.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}

func (m *defaultLeaderboardsModel) Count() (int64, error) {
	query := fmt.Sprintf("select count(*) as count from %s", m.table)

	var count int64
	err := m.CachedConn.QueryRowNoCache(&count, query)

	switch err {
	case nil:
		return count, nil
	case sqlc.ErrNotFound:
		return 0, ErrNotFound
	default:
		return 0, err
	}
}
